/*
 * @Description: 全宗reducer
 * @Author: Rfan
 * @Date: 2022-01-08 16:30:05
 * @LastEditTime: 2022-05-31 15:35:10
 */

import { delItemById, editItemById, insertItemAfter, updateItemById } from '@/utils/list';
import {
  ADD_LEVEL_BY_ID,
  ADD_METADATA,
  ARC_TYPE_LOADING,
  DELETE_METADATA,
  EDIT_BUSINESS,
  INIT_QUERY,
  METADATA_LOADING,
  METADATA_LOADING_FINISH,
  SET_ARC_TYPE_LIST,
  SET_METADATA_LIST,
  SET_QUERY,
  SET_SELECT_AT,
  SET_SELECT_FOND,
  SET_SELECT_LEVEL
} from '../constants';

export const MetadataBusinessReducer = (state, action) => {
  switch (action.type) {
    // 设置选中的全宗
    case SET_SELECT_FOND:
      return {
        ...state,
        selectFond: action.data
      };

    // 设置选中的档案类型
    case SET_SELECT_AT:
      return {
        ...state,
        selectAT: action.data
      };

    // 设置选中的层级
    case SET_SELECT_LEVEL:
      return {
        ...state,
        selectLevel: action.data
      };

    // 表格加载loading
    case ARC_TYPE_LOADING:
      return { ...state, loading: true };

    /**
     * @description: 加载表格数据及相关数据
     * @param {Array} data 表格数据
     * @return {*}
     */
    case SET_ARC_TYPE_LIST: {
      const ATList = action.data.map((item) => {
        item.treeName = item.atName;
        item.key = item.id;
        return item;
      });
      return {
        ...state,
        ATList
      };
    }

    /**
     * @description: 表格加载loading
     */
    case METADATA_LOADING:
      return { ...state, metadataLoading: true };

    /**
     * @description: 表格加载loading
     */
    case METADATA_LOADING_FINISH:
      return { ...state, metadataLoading: false };

    /**
     * @description: 加载元数据列表
     * @param {Array} data 表格数据
     */
    case SET_METADATA_LIST: {
      return {
        ...state,
        metadataList: action.data,
        metadataLoading: false
      };
    }

    /**
     * @description:加载表格数据及相关数据
     */
    case INIT_QUERY: {
      return {
        ...state,
        listQuery: action.data
      };
    }

    /**
     * @description: 设置表格数据及相关数据
     */
    case SET_QUERY: {
      const listQuery = { ...state.listQuery };
      action.info.forEach(({ key, value }) => {
        listQuery[key] = value;
      });

      return {
        ...state,
        listQuery
      };
    }

    /**
     * @description: 删除元数据条目
     */
    case EDIT_BUSINESS:
      return {
        ...state,
        metadataList: editItemById(action.data.id, action.data, state.metadataList)
      };

    default:
      console.log('untouched', action);
      return state;
  }
};
